package com.fit.carservice.pages;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.beans.UserBean;
import com.fit.enums.AccountRole;
import com.fit.interfaces.UserI;
import com.fit.service.UsersI;

public class AddUser {

	@Persist
	@Property
	private UserI newUser;
	
	@SetupRender
	public void createObject(){
		newUser = new UserBean();
		//dodati relaciju za service department!!!
	}
	@Property
	private UserI gridUser;
	
//	@Property
//	@Inject
//	private Block edit;
//	
//	@Property
//	@Inject
//	private Block congratulations;
	
	@Inject
	@Property
	private UsersI users;
	
	@Component(id="userInputForm")
	private Form userInputForm;
	
	@Component(id="userName")
	private TextField userNameField;
	
	@Component(id = "password")
	private PasswordField passwordField;
	
	@Component
	private Zone zoneSave;
	
	@Persist
	private String userName;
	
	@Persist
	private String password;
	
	@Persist
	private String password2;
	
	@Persist
	@Property
	private String fullName;
	
	
	@Persist
	@Property
	private String email;
	
	@Persist
	@Property
	private AccountRole role;
	
	@Inject
	private Messages messages;
	
	public void onValidate(){;
		if(!((userName == null) || (password == null) || (password2 ==null) ) ){
				
			if(!password.equals(password2)){
					userInputForm.recordError(passwordField, messages.get("passwords don't match"));
				}
				if(users.retriveSingleUser(getUserName()) != null){
					userInputForm.recordError(userNameField, messages.get("userName-exists"));
				}

		}
	}
	

	
	Object onSuccess(){
		newUser.executeUserCreation(fullName, userName, password, email, role);
		users.save(newUser);
		fullName = "";
		userName ="";
		password = "";
		email = "";
		role = null;
		return zoneSave.getBody();
	}
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}
	
}
